<?php
/**
 * 功能: 商品管理
 * User: 文丹
 * Date: 2018/7/27 0027
 * Time: 11:21
 */

namespace app\admin\controller;
use app\base\controller\Power;
use think\Db;
import('PHPExcel.PHPExcel', EXTEND_PATH);
class Goods extends Power{
    protected $beforeActionList = [
        'first'=>['except'=>'category_son, goods_search,recovery_search,search_order,refund,search_refund,hot']

    ];
    protected function first(){
        $result = $this->testing();
    }
    /**
     * 商品分类
     */
    public function category(){
        $category = Db::name('goods_type')->paginate(10);
        $count    = Db::name('goods_type')->count();
        $this->assign([
            'category'=>$category,
            'count'=>$count,
            'empty'=>'<tr class="text-c empty"><td colspan="6">暂无数据</td></tr>'
        ]);
        return $this->fetch('goods:category');
    }
    /**
     * 分类排序值设置
     */
    public function editSort(){
        $id = intval(input('id'));
        $sort = intval(input('sort'));
        if($sort<=0){
            return json(['msg'=>'排序值必须为正整数','ok'=>false]);
        }

        $sort_o =  Db::name('goods_type')->where('id',$id)->value('sort');
        $goods_type =  Db::name('goods_type')->where('id',$id)->find();

        $sort_o =  $goods_type['sort'];
        $sort_max = Db::name('goods_type')->max('sort');


        Db::startTrans();
        try{

            if($sort>$sort_max){
                $res = Db::name('goods_type')->where('id',$id)->update(['sort'=>$sort]);
            }elseif($sort<$sort_max){
                if($sort>$sort_o){
                    $res1 = Db::name('goods_type')
                        ->whereNotIn('id',$id)
                        ->where('sort','<=',$sort)
                        ->where('sort','>',$sort_o)
                        ->setDec('sort',1);
                }else{
                    $res1 = Db::name('goods_type')
                        ->whereNotIn('id',$id)
                        ->where('sort','<',$sort_o)
                        ->where('sort','>=',$sort)
                        ->setInc('sort',1);
                }

                $res = Db::name('goods_type')->where('id',$id)->update(['sort'=>$sort]);
            }elseif($sort=$sort_max){
                $res1 = Db::name('goods_type')
                    ->whereNotIn('id',$id)
                    ->where('sort','<=',$sort_max)
                    ->setDec('sort',1);
                $res = Db::name('goods_type')->where('id',$id)->update(['sort'=>$sort]);
            }

            // 提交事务
            Db::commit();
            return json(['msg'=>'设置成功','ok'=>true]);
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            $err = $e->getMessage();
            return json(['msg'=>$err,'ok'=>false]);
        }

    }
    /**
     *  分类添加 页面
     */
    public function categoryAdd(){

        $id = input('get.id');
        if($id){
            $type = Db::name('goods_type')->where('id',$id)->find();

            $this->assign('type',$type);
        }
        $category = Db::name('goods_type')->select();
        $this->assign([
            'category'=>$category
        ]);
        return $this->fetch('goods:category-add');
    }

    /**
     * 添加保存
     */
    public function category_hold(){
        $parent_id = intval(input('parent_id'));
        $name      = trim(input('name'));
        $icon      = trim(input('icon'));

        if(empty($name)){
            return json(['msg'=>'分类名不能为空！','ok'=>false]);
        }
        $data = [
            'parent_id'=>$parent_id,
            'name'=>$name,
            'icon'=>$icon
        ];

        $result = Db::name('goods_type')->insert($data);
        if($result){
            return json(['msg'=>'添加成功！','ok'=>true]);
        }else{
            json(['msg'=>'添加失败！','ok'=>false]);
        }
    }

    /**
     *  分类修改保存
     */
    public function category_save(){
        $name = trim(input('name'));
        $id   = intval(input('id'));
        $icon = trim(input('icon'));
        $parent_id = intval(input('parent_id'));
        if(empty($name)){
            return json(['msg'=>'分类名不能为空！','ok'=>false]);
        }
        $data = [
            'name'=>$name,
            'icon'=>$icon,
            'parent_id'=>$parent_id,
        ];

        $result = Db::name('goods_type')->where('id',$id)->update($data);
        if($result){
            return json(['msg'=>'修改成功！','ok'=>true]);
        }else{
           return json(['msg'=>'修改失败！','ok'=>false]);
        }
    }

    /**
     * 子分类页面
     */
    public function category_son(){
        $parent_id = input('id');
        $parent_name = Db::name('goods_type')->where('id',$parent_id)->value('name');
        $son = Db::name('goods_type')->where('parent_id',$parent_id)
            ->paginate(10,false,['query'=>request()->param()])
            ->each(function($item,$key){
            $item['parent_name'] = Db::name('goods_type')->where('id',$item['parent_id'])->value('name');
            return $item;
        });
        $count    = Db::name('goods_type')->where('parent_id',$parent_id)->count();
        $this->assign([
            'son'=>$son,
            'parent_name'=>$parent_name,
            'count'=>$count,
            'empty'=>'<tr class="text-c empty"><td colspan="7">暂无子分类</td></tr>'
        ]);
        return $this->fetch('goods:category-son');
    }

    /**
     * 分类停用
     */
    public function category_stop(){
        $id = intval(input('id'));

        if(is_numeric($id) && is_int($id+0) && ($id+0)>0 ){
            $result = Db::name('goods_type')->where('id',$id)->update(['is_down'=>2]);
            if($result){
                return json(['msg'=>'分类已停用！','ok'=>true]);
            }else{
                json(['msg'=>'停用失败！','ok'=>false]);
            }

        }else{
            return json(['msg'=>'id必须为正整数！','ok'=>false]);
        }

    }
    /**
     *  分类 启用
     */
    public function category_start($id){
        $id = intval(input('id'));
        if(is_numeric($id) && is_int($id+0) && ($id+0)>0 ){
            $result = Db::name('goods_type')->where('id',$id)->update(['is_down'=>1]);
            if($result){
                return json(['msg'=>'分类已启用！','ok'=>true]);
            }else{
                json(['msg'=>'启用失败！','ok'=>false]);
            }

        }else{
            return json(['msg'=>'id必须为正整数！','ok'=>false]);
        }

    }
    /**
     * 删除 分类
     * @param $id
     */
    public function category_del($id){
        $id = intval(input('id'));
        if(is_numeric($id) && is_int($id+0) && ($id+0)>0 ){
            $check  = Db::name('goods')->where('gt_id',$id)->find();
            if($check){
                json(['msg'=>'该分类已有商品使用，请修改商品后再删除！','ok'=>false]);
            }
            $result = Db::name('goods_type')->where('id',$id)->delete();
            if($result){
                return json(['msg'=>'分类已删除！','ok'=>true]);
            }else{
                json(['msg'=>'删除失败！','ok'=>false]);
            }

        }else{
            return json(['msg'=>'id必须为正整数！','ok'=>false]);
        }
    }


    /**
     * 商品板块
     */
    public function block(){
        $block = Db::name('goods_block')->select();
        $count = Db::name('goods_block')->count();
        $this->assign([
            'block'=>$block,
            'count'=>$count,
            'empty'=>'<tr class="text-c empty"><td colspan="6">暂无数据</td></tr>'
        ]);
        return view('');
    }

    /**
     * 板块添加/修改 界面
     */
    public function block_add(){
        $id = intval(input('id'));
        if($id){
            $block = Db::name('goods_block')->where('id',$id)->find();
            $this->assign([
                'block'=>$block
            ]);
        }
        return view('');
    }
    public function block_hold(){
        $name   = trim(input('name'));
        $is_tao = intval(input('is_tao'));
        $logo   = trim(input('logo'));
        if(empty($name)||empty($logo)){
            return json(['msg'=>'请填写完整的数据！','ok'=>false]);
        }
        $check = Db::name('goods_block')->where('name',$name)->find();
        if($check){
            return json(['msg'=>'板块名不能重复！','ok'=>false]);
        }
        $res = Db::name('goods_block')->insert(['name'=>$name,'is_tao'=>$is_tao,'logo'=>$logo]);
        if($res){
            return json(['msg'=>'添加成功！','ok'=>true]);
        }else{
            return json(['msg'=>'添加失败！','ok'=>false]);
        }
    }
    public function block_save(){
        $id     = intval(input('id'));
        $name   = trim(input('name'));
        $is_tao = intval(input('is_tao'));
        $logo   = trim(input('logo'));
        if(empty($name)||empty($logo)){
            return json(['msg'=>'请填写完整的数据！','ok'=>false]);
        }
        $check = Db::name('goods_block')->where('name',$name)->whereNotIn('id',$id)->find();
        if($check){
            return json(['msg'=>'板块名不能重复！','ok'=>false]);
        }
        $res = Db::name('goods_block')->where('id',$id)->update(['name'=>$name,'is_tao'=>$is_tao,'logo'=>$logo]);
        if($res){
            return json(['msg'=>'修改成功！','ok'=>true]);
        }else{
            return json(['msg'=>'你没有做出修改！','ok'=>false]);
        }
    }

    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

    /**
     * 商品列表
     */
    public function goods_list(){
        $goods = Db::table('goods')
            ->whereTime('goods_end_time','>=',time())
            ->order('id desc')
            ->paginate(10,false,['query'=>request()->param()])->each(function($item,$key){
                $gt_id = $item['gt_id'];
                $gb_id = $item['gb_id'];
                if(!empty($gt_id)){
                    $item['gt_name'] = Db::name('goods_type')->where('id',$gt_id)->value('name');
                }
                if(!empty($gb_id)){
                    $item['gb_name'] = Db::name('icon')->where('id',$gb_id)->value('name');
                }
                return $item;

            });
        /*echo '<pre>';
        print_r($goods);die;*/
        $count =  Db::table('goods')
           ->whereTime('goods_end_time','>=',time())
            ->count();
        $category = Db::name('goods_type')->where('parent_id',0)->select();
        $block = Db::name('icon')->where('is_goods',1)->select();
        $this->assign([
            'empty'=>'<tr class="text-c va-m empty"><td colspan="22">暂无数据</td></tr>',
            'goods'=>$goods,
            'count'=>$count,
            'block'=>$block,
            'category'=>$category
        ]);

        return $this->fetch('goods:goods-list');
    }

    /**
     * 商品搜索
     */
    public function goods_search(){
        $opt   = intval(input('opt'));
        if($opt<=0){
            return json(['msg'=>'请求不合法！','ok'=>false]);
        }

        $gt_id = intval(input('gt_id'));
        $gb_id = intval(input('gb_id'));
        $gt_name = trim(input('gt_name'));
        $start_price = trim(input('start_price'));
        $end_price = trim(input('end_price'));
        $goods_title = trim(input('goods_title'));

        $category = Db::name('goods_type')->where('parent_id',0)->select();
        $block = Db::name('icon')->where('is_goods',1)->select();
        if($opt==1){
            //商品分类搜索
            if(empty($gt_id)){
                return json(['msg'=>'搜索条件不能为空！','ok'=>false]);
            }
            $goods = Db::table('goods')
                ->where('gt_id',$gt_id)
                ->whereTime('goods_end_time','>=',time())
                ->paginate(10,false,['query'=>request()->param()])->each(function($item,$key){
                    $gt_id = $item['gt_id'];
                    $gb_id = $item['gb_id'];
                    if(!empty($gt_id)){
                        $item['gt_name'] = Db::name('goods_type')->where('id',$gt_id)->value('name');
                    }
                    if(!empty($gb_id)){
                        $item['gb_name'] = Db::name('icon')->where('id',$gb_id)->value('name');
                    }
                    return $item;

                });
            $count =  Db::table('goods')
                ->where('gt_id',$gt_id)
                ->whereTime('goods_end_time','>=',time())
                ->count();
            /* echo '<pre>';
                    print_r($goods);die;*/
            if(!empty($goods[0])){
                $this->assign([
                    'goods'=>$goods,
                    'count'=>$count,
                    'block'=>$block,
                    'category'=>$category
                ]);
                return $this->fetch('goods:goods-list',['gt_id'=>$gt_id,'gb_id'=>$gb_id,'gt_name'=>$gt_name,'goods_title'=>$goods_title]);
            }else{
                return json(['msg'=>'没有符合条件的搜索结果！','ok'=>false]);
            }
        }elseif($opt==2){
            //商品标题搜索
            if(empty($goods_title)){
                return json(['msg'=>'搜索条件不能为空！','ok'=>false]);
            }
            $goods = Db::table('goods')
                ->where('goods_title','like','%'.$goods_title.'%')
                ->whereTime('goods_end_time','>=',time())
                ->paginate(10,false,['query'=>request()->param()])->each(function($item,$key){
                    $gt_id = $item['gt_id'];
                    $gb_id = $item['gb_id'];
                    if(!empty($gt_id)){
                        $item['gt_name'] = Db::name('goods_type')->where('id',$gt_id)->value('name');
                    }
                    if(!empty($gb_id)){
                        $item['gb_name'] = Db::name('icon')->where('id',$gb_id)->value('name');
                    }
                    return $item;


                });
            $count = Db::table('goods')
                ->where('goods_title','like','%'.$goods_title.'%')
                ->whereTime('goods_end_time','>=',time())
                ->count();
            /*echo '<pre>';
                   print_r($goods);die;*/
            if(!empty($goods[0])){
                $this->assign([
                    'goods'=>$goods,
                    'count'=>$count,
                    'block'=>$block,
                    'category'=>$category
                ]);
                return $this->fetch('goods:goods-list',['gt_id'=>$gt_id,'gb_id'=>$gb_id,'gt_name'=>$gt_name,'goods_title'=>$goods_title]);
            }else{
                return json(['msg'=>'没有符合条件的搜索结果！','ok'=>false]);
            }

        }elseif($opt==3){
            //商品板块搜索
            if(empty($gb_id)){
                return json(['msg'=>'搜索条件不能为空！','ok'=>false]);
            }
            $goods = Db::table('goods')
                ->where('gb_id',$gb_id)
                ->whereTime('goods_end_time','>=',time())
                ->paginate(10,false,['query'=>request()->param()])->each(function($item,$key){
                    $gt_id = $item['gt_id'];
                    $gb_id = $item['gb_id'];
                    if(!empty($gt_id)){
                        $item['gt_name'] = Db::name('goods_type')->where('id',$gt_id)->value('name');
                    }
                    if(!empty($gb_id)){
                        $item['gb_name'] = Db::name('icon')->where('id',$gb_id)->value('name');
                    }
                    return $item;


                });
            $count =  Db::table('goods')
                ->where('gb_id',$gb_id)
                ->whereTime('goods_end_time','>=',time())
                ->count();
            /* echo '<pre>';
                    print_r($goods);die;*/
            if(!empty($goods[0])){
                $this->assign([
                    'goods'=>$goods,
                    'count'=>$count,
                    'block'=>$block,
                    'category'=>$category
                ]);
                return $this->fetch('goods:goods-list',['gt_id'=>$gt_id,'gb_id'=>$gb_id,'gt_name'=>$gt_name,'goods_title'=>$goods_title]);
            }else{
                return json(['msg'=>'没有符合条件的搜索结果！','ok'=>false]);
            }
        }elseif($opt==4){
            //价格范围搜索
            if(empty($start_price)&&empty($end_price)){
                return json(['msg'=>'搜索条件不能为空！','ok'=>false]);
            }

            $goods = model('Goods')->searchPrice($start_price,$end_price);
            $count = model('Goods')->countPrice($start_price,$end_price);
            if(!empty($goods[0])){
                $this->assign([
                    'goods'=>$goods,
                    'count'=>$count,
                    'block'=>$block,
                    'category'=>$category
                ]);
                return $this->fetch('goods:goods-list',
                    ['gt_id'=>$gt_id,
                        'gb_id'=>$gb_id,
                        'gt_name'=>$gt_name,
                        'start_price'=>$start_price,
                        'end_price'=>$end_price,
                        'goods_title'=>$goods_title]);
            }else{
                return json(['msg'=>'没有符合条件的搜索结果！','ok'=>false]);
            }
        }
        else{
            return json(['msg'=>'搜索不合法！','ok'=>false]);
        }
    }

    /**
     * 商品下架
     */
    public function stop(){
        $goods_id = trim(input('id'));
        if(empty($goods_id)){
            return json(['msg'=>'id不能为空','ok'=>false]);
        }
         $result = Db::name('goods')->where('goods_id',$goods_id)->update(['is_down'=>2]);
       if($result){
            return json(['msg'=>'已下架','ok'=>true]);
        }else{
            return json(['msg'=>'下架失败','ok'=>false]);
        }
    }
    /**
     * 商品发布
     */
    public function start(){
        $goods_id = trim(input('id'));
        if(empty($goods_id)){
            return json(['msg'=>'id不能为空','ok'=>false]);
        }
        $result = Db::name('goods')->where('goods_id',$goods_id)->update(['is_down'=>1]);
        if($result){
            return json(['msg'=>'已发布','ok'=>true]);
        }else{
            return json(['msg'=>'发布失败','ok'=>false]);
        }
    }

    /**
     * 设为精品
     */
    public function choice(){
        $goods_id = trim(input('goods_id'));
        if(empty($goods_id)){
            return json(['msg'=>'goods_id不能为空','ok'=>false]);
        }
        $result = Db::name('goods')->where('goods_id',$goods_id)->update(['is_choice'=>1]);
        if($result){
            return json(['msg'=>'已设为精品','ok'=>true]);
        }else{
            return json(['msg'=>'设置失败','ok'=>false]);
        }
    }

    /**
     * 取消精品设置
     */
    public function plain(){
        $goods_id = trim(input('goods_id'));
        if(empty($goods_id)){
            return json(['msg'=>'goods_id不能为空','ok'=>false]);
        }
        $result = Db::name('goods')->where('goods_id',$goods_id)->update(['is_choice'=>2]);
        if($result){
            return json(['msg'=>'已取消设置','ok'=>true]);
        }else{
            return json(['msg'=>'设置失败','ok'=>false]);
        }
    }

    /**
     * 商品加入回收站
     */
    public function productDel(){
        $id = intval(input('id'));
        if(empty($id)){
            return json(['msg'=>'id不能为空','ok'=>false]);
        }
        $end_time  = strtotime ("-1 day", time());
        $result = Db::name('goods')->where('id',$id)->update(['goods_end_time'=>$end_time]);

        if($result){
            return json(['msg'=>'已回收','ok'=>true]);
        }else{
            return json(['msg'=>'回收失败','ok'=>false]);
        }
    }

    /**
     * 商品批量回收
     */
    public function goodsDatadel(){
        $id = input('id/a');
        if(empty($id)){
            return json(['msg'=>'id不能为空','ok'=>false]);
        }
        $end_time  = strtotime ("-1 day", time());
        $result = Db::name('goods')->whereIn('id',$id)->update(['goods_end_time'=>$end_time]);
        if($result){
            return json(['msg'=>'已删除','ok'=>true]);
        }else{
            return json(['msg'=>'删除失败','ok'=>false]);
        }
    }
    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

    /**
     * 过期商品 管理
     */
    public function over_goods(){
        $goods = Db::table('goods')
            ->whereTime('goods_end_time','<',time())
            ->order('goods_end_time desc')
            ->paginate(10,false,['query'=>request()->param()])->each(function($item,$key){
                $gt_id = $item['gt_id'];
                $gb_id = $item['gb_id'];
                if(!empty($gt_id)){
                    $item['gt_name'] = Db::name('goods_type')->where('id',$gt_id)->value('name');
                }
                if(!empty($gb_id)){
                    $item['gb_name'] = Db::name('icon')->where('id',$gb_id)->value('name');
                }
                return $item;

            });
        /*echo '<pre>';
        print_r($goods);die;*/
        $count =  Db::table('goods')
            ->whereTime('goods_end_time','<',time())
            ->count();
        $category = Db::name('goods_type')->where('parent_id',0)->select();

        $this->assign([
            'empty'=>'<tr class="text-c va-m empty"><td colspan="13">暂无数据</td></tr>',
            'goods'=>$goods,
            'count'=>$count,
            'category'=>$category
        ]);
        return $this->fetch('goods:over_goods');
    }

    /**
     * 过期商品搜索
     */
    public function recovery_search(){
        $opt   = intval(input('opt'));
        if($opt<=0){
            return json(['msg'=>'请求不合法！','ok'=>false]);
        }

        $gt_id = intval(input('gt_id'));
        $gt_name = trim(input('gt_name'));
        $goods_title = trim(input('goods_title'));
        $category = Db::name('goods_type')->where('parent_id',0)->select();
        if($opt==1){
            //商品分类搜索
            if(empty($gt_id)){
                return json(['msg'=>'搜索条件不能为空！','ok'=>false]);
            }
            $goods = Db::table('goods')
                ->where('gt_id',$gt_id)
                ->whereTime('goods_end_time','<=',time())
                ->paginate(10,false,['query'=>request()->param()])->each(function($item,$key){
                    $gt_id = $item['gt_id'];
                    $gb_id = $item['gb_id'];
                    if(!empty($gt_id)){
                        $item['gt_name'] = Db::name('goods_type')->where('id',$gt_id)->value('name');
                    }
                    if(!empty($gb_id)){
                        $item['gb_name'] = Db::name('icon')->where('id',$gb_id)->value('name');
                    }
                    return $item;

                });
            $count =  Db::table('goods')
                ->where('gt_id',$gt_id)
                ->whereTime('goods_end_time','<=',time())
                ->count();

            if(!empty($goods[0])){
                $this->assign([
                    'goods'=>$goods,
                    'count'=>$count,
                    'category'=>$category
                ]);
                return $this->fetch('goods:over_goods',['gt_id'=>$gt_id,'gt_name'=>$gt_name,'goods_title'=>$goods_title]);
            }else{
                return json(['msg'=>'没有符合条件的搜索结果！','ok'=>false]);
            }
        }elseif($opt==2){
            //商品标题搜索
            if(empty($goods_title)){
                return json(['msg'=>'搜索条件不能为空！','ok'=>false]);
            }
            $goods = Db::table('goods')
                ->where('goods_title','like','%'.$goods_title.'%')
                ->whereTime('goods_end_time','<=',time())
                ->paginate(10,false,['query'=>request()->param()])->each(function($item,$key){
                    $gt_id = $item['gt_id'];
                    $gb_id = $item['gb_id'];
                    if(!empty($gt_id)){
                        $item['gt_name'] = Db::name('goods_type')->where('id',$gt_id)->value('name');
                    }
                    if(!empty($gb_id)){
                        $item['gb_name'] = Db::name('icon')->where('id',$gb_id)->value('name');
                    }
                    return $item;

                });
            $count = Db::table('goods')
                ->where('goods_title','like','%'.$goods_title.'%')
                ->whereTime('goods_end_time','<=',time())
                ->count();
            /*echo '<pre>';
                   print_r($goods);die;*/
            if(!empty($goods[0])){
                $this->assign([
                    'goods'=>$goods,
                    'count'=>$count,
                    'category'=>$category
                ]);
                return $this->fetch('goods:over_goods',['gt_id'=>$gt_id,'gt_name'=>$gt_name,'goods_title'=>$goods_title]);
            }else{
                return json(['msg'=>'没有符合条件的搜索结果！','ok'=>false]);
            }

        }
        else{
            return json(['msg'=>'搜索不合法！','ok'=>false]);
        }
    }

    /**
     * 过期商品删除
     */
    public function product_del(){
        $id = intval(input('id'));
        if(empty($id)){
            return json(['msg'=>'id必须为正整数','ok'=>false]);
        }
        $result = Db::name('goods')->where('id',$id)->delete();
        if($result){
            return json(['msg'=>'已删除','ok'=>true]);
        }else{
            return json(['msg'=>'删除失败','ok'=>false]);
        }
    }
    /**
     * 过期商品 批量删除
     */
    public function productDatadel(){
        $id = input('id/a');
        if(empty($id)){
            return json(['msg'=>'id不能为空','ok'=>false]);
        }
        $result = Db::name('goods')->whereIn('id',$id)->delete();
        if($result){
            return json(['msg'=>'已删除','ok'=>true]);
        }else{
            return json(['msg'=>'删除失败','ok'=>false]);
        }
    }
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

/**
 * 订单管理
 */
 public function goods_order(){
     $orders = Db::name('goods_order')
         ->order('id desc')
         ->paginate(10,false,['query'=>request()->param()])->each(function($item,$key){
             if(!empty($item['user_id'])){
                 $item['phone'] = Db::name('user')->where('id',$item['user_id'])->value('phone');

             }else{
                 $item['phone'] = '';
             }
             return $item;
         });
     /*echo "<pre>";
     print_r($orders);
     die;*/
     $count = Db::name('goods_order')->count();
     $this->assign([
         'orders'=>$orders,
         'count'=>$count,
         'empty'=>'<tr class="text-c va-m empty"><td colspan="13">暂无数据</td></tr>'
     ]);
     return $this->fetch('goods:order');
}

    public function search_order(){
        $change = intval(input('change'));
        $logmax = trim(input('logmax'));
        $logmin = trim(input('logmin'));
        $state = intval(input('state'));
        $common = trim(input('common'));

        if($change==1){
            //成交时间
            if(empty($logmax)&&empty($logmin)){
                return json(['msg'=>'搜索条件不能为空1','ok'=>false]);
            }

        }
        elseif($change==3){
            //订单号
            if(empty($common)){
                return json(['msg'=>'搜索条件不能为空2','ok'=>false]);
            }

         }elseif($change==4){
            if(empty($logmax)&&empty($logmin)){
                return json(['msg'=>'搜索条件不能为空3','ok'=>false]);
            }
         }
        $orders = model('GoodsOrder')->searchOrder($change,$logmax,$logmin,$state,$common);

        $count = model('GoodsOrder')->searchcount($change,$logmax,$logmin,$state,$common);

        if(!empty($orders[0])){
            $this->assign([
                'orders'=>$orders,
                'count'=>$count,
                'empty'=>'<tr class="text-c va-m empty"><td colspan="13">暂无数据</td></tr>'
            ]);
            return $this->fetch('goods:order',['change'=>$change,'logmax'=>$logmax,'logmin'=>$logmin,'state'=>$state,'common'=>$common]);
        }else{
            return json(['msg'=>'没有符合条件的结果！','ok'=>false]);
        }

    }


    /**
     * 添加订单
     */
    public function order_add(){
        $objPHPExcel = new \PHPExcel();
        //获取表单上传文件
        $file = request()->file('excel');
        //  print_r($file);die;
        $info = $file->validate(['size'=>10485760,'ext'=>'xlsx,xls,csv'])->move(ROOT_PATH . 'public' . DS . 'excel');
        if($info){
            $exclePath = $info->getSaveName();  //获取文件名
            $file_name = ROOT_PATH . 'public' . DS . 'excel' . DS . $exclePath;   //上传文件的地址
            $objReader =\PHPExcel_IOFactory::createReader('Excel2007');
            if(!$objReader->canRead($file_name)) {
                $objReader = \PHPExcel_IOFactory::createReader('Excel5');
            }
            $obj_PHPExcel =$objReader->load($file_name, $encode = 'utf-8');  //加载文件内容,编码utf-8

            $excel_array=$obj_PHPExcel->getsheet(0)->toArray();   //转换为数组格式
            array_shift($excel_array);  //删除第一个数组(标题);
            // print_r($excel_array);die;
            $data =  $datas = [];
            $i    = 0;
            foreach($excel_array as $k=>$v) {
                $data['create_time'] = $v[0];
                $data['click_time'] = $v[1];
                $data['info'] = $v[2];
                $data['goods_id'] = $v[3];
                $data['shop'] = $v[4];
                $data['amount'] = $v[5];
                $data['price'] = $v[6];
                $data['nick'] = $v[7];

                if($v[8]=="订单付款"){
                    $data['state']  = 1;
                }elseif($v[8]=="订单结算"){
                    $data['state'] = 2;
                }elseif($v[8]=="订单失效"){
                    $data['state'] = 3;
                }elseif($v[8]=="订单成功"){
                    $data['state'] = 4;
                }else{
                    $data['state'] = 0;
                }
                //订单类型，1天猫，0淘宝

                if($v[9]=="淘宝"){
                    $data['user_type'] = 0;
                }else{
                    $data['user_type'] = 1;
                }

                $data['income_rate'] = $v[10]*100;//收入比率
                $data['divide_tate'] = $v[11]*100;//分成比率
                $data['pay'] = $v[12];//付款金额
                $data['effect'] = $v[13];//效果预估
                $data['settle'] = $v[14];//结算金额
                $data['expect'] = $v[15];//预计收入
                $data['finish_time'] = $v[16];//结算时间
                $data['yj_rate'] = $v[17]*100;//佣金比率
                $data['yj_sum'] = $v[18];//佣金金额

                $data['member_actual'] = round($data['yj_sum']/2,2);//会员佣金实际收入

                $member_expect = Db::name('goods')
                    ->where('goods_id',$data['goods_id'])
                    ->value('member_yongjin');
                $data['member_expect'] =  $data['amount']*$member_expect;//预计会员佣金

                $data['subsidy_rate'] = $v[19]*100;//补贴比率
                $data['subsidy'] = $v[20];//补贴金额
                $data['order_num'] = $v[21];//淘宝订单号
                $data['goods_type'] = $v[22];//商品分类
                $data['adzone_id'] = $v[23];//广告位id
                $data['user_id'] = Db::name('pid')->where('adzone_id', $data['adzone_id'])->value('user_id');
                $data['adzone_name'] = $v[24];

                $check = Db::name('goods_order')
                    ->where('goods_id',$data['goods_id'])
                    ->where('order_num',$data['order_num'])
                    ->find();
                if ($data['state'] == 2) {
                    //订单结算
                    $user = Db::name('user')->where('id', $data['user_id'])->find();
                    $amount = $data['member_actual'];
                    $arr = [
                        'user_id' => $data['user_id'],
                        'commission' => $amount,
                        'order_num' => $data['order_num'],
                        'finish_time' => $data['finish_time'],
                        'time' => time(),
                        'state' => 1,//1收入，2支出
                        'type' => 1,//1自己订单收入，2粉丝提成收入，3用户提现支出
                        'remark' => '订单' . $data['order_num'] . '收入'
                    ];
                    $check_profit = Db::name('profit')
                        ->where('user_id',$data['user_id'])
                        ->where('order_num',$data['order_num'])
                        ->find();
                    if (empty($check_profit)) {
                        Db::name('profit')->insert($arr);
                        Db::name('user')->where('id', $data['user_id'])->setInc('total', $amount);
                        Db::name('user')->where('id', $data['user_id'])->setInc('commission', $amount);

                        //找父级
                        $parent_id = $user['parent_id'];
                        if($parent_id) {
                            $parent = Db::name('user')->where('id', $parent_id)->find();
                            $ticheng = 0;
                            if ($parent['status'] == 3) {
                                //初级合伙人
                                $rule = Db::name('partner_rule')->where('status', 3)->find();
                                $level1 = $rule['level1'] / 100;
                                $ticheng = round($amount * $level1, 2);
                            } elseif ($parent['status'] == 4) {
                                //高级合伙人
                                $rule = Db::name('partner_rule')->where('status', 4)->find();
                                $level1 = $rule['level1'] / 100;
                                $ticheng = round($amount * $level1, 2);

                            }
                            $arr1 = [
                                'user_id' => $parent_id,
                                'commission' => $ticheng,
                                'order_num' => $data['order_num'],
                                'finish_time' => $data['finish_time'],
                                'time' => time(),
                                'state' => 1,//1收入，2支出
                                'type' => 2,//1自己订单收入，2粉丝提成收入，3用户提现支出
                                'remark' => '粉丝' . $data['user_id'] . '订单' . $data['order_num'] . '收入'
                            ];
                            $check_profit = Db::name('profit')
                                ->where('user_id',$parent_id)
                                ->where('order_num',$data['order_num'])
                                ->find();
                            if(empty($check_profit)){
                                Db::name('profit')->insert($arr1);
                                Db::name('user')->where('id', $parent_id)->setInc('total', $ticheng);
                                Db::name('user')->where('id', $parent_id)->setInc('commission', $ticheng);
                                Db::name('user')->where('id', $parent_id)->setInc('rebate', $ticheng);
                            }

                            $grandsire = Db::name('user')->where('id', $parent['parent_id'])->find();
                            if ($grandsire) {
                                //祖籍
                                $t2 = 0;
                                if ($grandsire['status'] == 3) {
                                    //初级合伙人
                                    $rule = Db::name('partner_rule')->where('status', 3)->find();
                                    $level2 = $rule['level2'] / 100;
                                    $t2 = round($amount * $level2, 2);
                                } elseif ($grandsire['status'] == 4) {
                                    //高级合伙人
                                    $rule = Db::name('partner_rule')->where('status', 4)->find();
                                    $level2 = $rule['level2'] / 100;
                                    $t2 = round($amount * $level2, 2);

                                }
                                $arr2 = [
                                    'user_id' => $grandsire['id'],
                                    'commission' => $t2,
                                    'order_num' => $data['order_num'],
                                    'finish_time' => $data['finish_time'],
                                    'time' => time(),
                                    'state' => 1,//1收入，2支出
                                    'type' => 2,//1自己订单收入，2粉丝提成收入，3用户提现支出
                                    'remark' => '粉丝' . $data['user_id'] . '订单' . $data['order_num'] . '收入'
                                ];
                                $check_profit = Db::name('profit')
                                    ->where('user_id',$grandsire['id'])
                                    ->where('order_num',$data['order_num'])
                                    ->find();
                                if(empty($check_profit)){
                                    Db::name('profit')->insert($arr2);
                                    Db::name('user')->where('id', $grandsire['id'])->setInc('total', $t2);
                                    Db::name('user')->where('id', $grandsire['id'])->setInc('commission', $t2);
                                    Db::name('user')->where('id', $grandsire['id'])->setInc('rebate', $t2);
                                }

                            }
                        }

                    }

                }

                if (!empty($check)) {
                    $success = Db::name('goods_order')->where('goods_id', $data['goods_id'])->where('order_num', $data['order_num'])->update($data);
                    if ($success) {
                        return json(['msg' => '插入或更新成功！', 'ok' => true]);
                    }
                } else {
                    $datas[] = $data;
                }
                $i++;
            }
            if(empty($datas)){
                return json(['msg' => '插入或更新成功！', 'ok' => true]);
            }else{

                Db::startTrans();
                try{
                    $success = Db::name('goods_order')->insertAll($datas); //批量插入数据

                    foreach($datas as $k =>$v){
                        if ($v['state'] == 2) {
                            //订单结算
                            $user = Db::name('user')->where('id', $v['user_id'])->find();
                            $amount = $v['member_actual'];
                            /* dump($amount);
                             die;*/
                            if($amount){
                                $arr = [
                                    'user_id' => $v['user_id'],
                                    'commission' => $amount,
                                    'time' => time(),
                                    'finish_time' => $v['finish_time'],
                                    'order_num' => $v['order_num'],
                                    'state' => 1,//1收入，2支出
                                    'type' => 1,//1自己订单收入，2粉丝提成收入，3用户提现支出
                                    'remark' => '订单' . $v['order_num'] . '收入'
                                ];
                                $check_profit = Db::name('profit')
                                    ->where('user_id',$v['user_id'])
                                    ->where('order_num',$v['order_num'])
                                    ->find();
                                if (empty($check_profit)) {
                                    Db::name('profit')->insert($arr);
                                    Db::name('user')->where('id', $v['user_id'])->setInc('total', $amount);
                                    Db::name('user')->where('id', $v['user_id'])->setInc('commission', $amount);

                                    $parent_id = $user['parent_id'];
                                    if($parent_id) {
                                        $parent = Db::name('user')->where('id', $parent_id)->find();
                                        $ticheng = 0;
                                        if ($parent['status'] == 3) {
                                            //初级合伙人
                                            $rule = Db::name('partner_rule')->where('status', 3)->find();
                                            $level1 = $rule['level1'] / 100;

                                            $ticheng = round($amount * $level1, 2);
                                        } elseif ($parent['status'] == 4) {
                                            //高级合伙人
                                            $rule = Db::name('partner_rule')->where('status', 4)->find();
                                            $level1 = $rule['level1'] / 100;
                                            $ticheng = round($amount * $level1, 2);

                                        }
                                        if ($ticheng) {
                                            $arr1 = [
                                                'user_id' => $parent_id,
                                                'commission' => $ticheng,
                                                'time' => time(),
                                                'finish_time' => $v['finish_time'],
                                                'order_num' => $v['order_num'],
                                                'state' => 1,//1收入，2支出
                                                'type' => 2,//1自己订单收入，2粉丝提成收入，3用户提现支出
                                                'remark' => '粉丝' . $v['user_id'] . '订单' . $v['order_num'] . '收入'
                                            ];

                                            $check_profit = Db::name('profit')
                                                ->where('user_id',$parent_id)
                                                ->where('order_num',$v['order_num'])
                                                ->find();
                                            if(empty($check_profit)){
                                                Db::name('profit')->insert($arr1);
                                                Db::name('user')->where('id', $parent_id)->setInc('total', $ticheng);
                                                Db::name('user')->where('id', $parent_id)->setInc('commission', $ticheng);
                                                Db::name('user')->where('id', $parent_id)->setInc('rebate', $ticheng);
                                            }


                                        }

                                        $grandsire = Db::name('user')->where('id', $parent['parent_id'])->find();
                                        if ($grandsire) {
                                            //祖籍
                                            $t2 = 0;
                                            if ($grandsire['status'] == 3) {
                                                //初级合伙人
                                                $rule = Db::name('partner_rule')->where('status', 3)->find();
                                                $level2 = $rule['level2'] / 100;
                                                $t2 = round($amount * $level2, 2);
                                            } elseif ($grandsire['status'] == 4) {
                                                //高级合伙人
                                                $rule = Db::name('partner_rule')->where('status', 4)->find();
                                                $level2 = $rule['level2'] / 100;
                                                $t2 = round($amount * $level2, 2);

                                            }
                                            if ($t2) {
                                                $arr2 = [
                                                    'user_id' => $grandsire['id'],
                                                    'commission' => $t2,
                                                    'time' => time(),
                                                    'finish_time' => $v['finish_time'],
                                                    'order_num' => $v['order_num'],
                                                    'state' => 1,//1收入，2支出
                                                    'type' => 2,//1自己订单收入，2粉丝提成收入，3用户提现支出
                                                    'remark' => '粉丝' . $v['user_id'] . '订单' . $v['order_num'] . '收入'
                                                ];
                                                $check_profit = Db::name('profit')
                                                    ->where('user_id',$grandsire['id'])
                                                    ->where('order_num',$v['order_num'])
                                                    ->find();
                                                if(empty($check_profit)){
                                                    Db::name('profit')->insert($arr2);
                                                    Db::name('user')->where('id', $grandsire['id'])->setInc('total', $t2);
                                                    Db::name('user')->where('id', $grandsire['id'])->setInc('commission', $t2);
                                                    Db::name('user')->where('id', $grandsire['id'])->setInc('rebate', $t2);
                                                }


                                            }

                                        }
                                    }
                                }

                            }


                        }

                    }

                    // 提交事务
                    Db::commit();
                    $error=$i-$success;
                    return json(['msg'=>"总{$i}条，成功{$success}条，失败{$error}条。",'ok'=>true]);
                } catch (\Exception $e) {
                    // 回滚事务
                    Db::rollback();
                    $error = $e->getMessage();
                    return json(['msg'=>$error,'ok'=>false]);
                }
            }

        }else{
            // 上传失败获取错误信息
            $error = $file->getError();
            return json(['msg'=>$error,'ok'=>false]);
        }
    }


    public function order_add1(){
        $objPHPExcel = new \PHPExcel();
        //获取表单上传文件
        $file = request()->file('excel');
      //  print_r($file);die;
        $info = $file->validate(['size'=>10485760,'ext'=>'xlsx,xls,csv'])->move(ROOT_PATH . 'public' . DS . 'excel');
        if($info){
            $exclePath = $info->getSaveName();  //获取文件名
            $file_name = ROOT_PATH . 'public' . DS . 'excel' . DS . $exclePath;   //上传文件的地址
            $objReader =\PHPExcel_IOFactory::createReader('Excel2007');
            if(!$objReader->canRead($file_name)) {
                $objReader = \PHPExcel_IOFactory::createReader('Excel5');
            }
            $obj_PHPExcel =$objReader->load($file_name, $encode = 'utf-8');  //加载文件内容,编码utf-8

            $excel_array=$obj_PHPExcel->getsheet(0)->toArray();   //转换为数组格式
            array_shift($excel_array);  //删除第一个数组(标题);
          // print_r($excel_array);die;
            $data =  $datas = [];
            $i    = 0;
            foreach($excel_array as $k=>$v) {
                $data['create_time'] = $v[0];
                $data['click_time'] = $v[1];
                $data['info'] = $v[2];
                $data['goods_id'] = $v[3];
                $data['shop'] = $v[4];
                $data['amount'] = $v[5];
                $data['price'] = $v[6];
                $data['nick'] = $v[7];

                if($v[8]=="订单付款"){
                    $data['state']  = 1;
                }elseif($v[8]=="订单结算"){
                    $data['state'] = 2;
                }elseif($v[8]=="订单失效"){
                    $data['state'] = 3;
                }elseif($v[8]=="订单成功"){
                    $data['state'] = 4;
                }else{
                    $data['state'] = 0;
                }
                //订单类型，1天猫，0淘宝

                if($v[9]=="淘宝"){
                    $data['user_type'] = 0;
                }else{
                    $data['user_type'] = 1;
                }

                $data['income_rate'] = $v[10]*100;//收入比率
                $data['divide_tate'] = $v[11]*100;//分成比率
                $data['pay'] = $v[12];//付款金额
                $data['effect'] = $v[13];//效果预估
                $data['settle'] = $v[14];//结算金额
                $data['expect'] = $v[15];//预计收入
                $data['finish_time'] = $v[16];//结算时间
                $data['yj_rate'] = $v[17]*100;//佣金比率
                $data['yj_sum'] = $v[18];//佣金金额

                $data['member_actual'] = round($data['yj_sum']*$data['amount']/2,2);//会员佣金实际收入

                $data['member_expect'] = $data['pay']*$data['pay']*$data['yj_rate']/100;//预计会员佣金

                $data['subsidy_rate'] = $v[19]*100;//补贴比率
                $data['subsidy'] = $v[20];//补贴金额
                $data['order_num'] = $v[21];//淘宝订单号
                $data['goods_type'] = $v[22];//商品分类
                $data['adzone_id'] = $v[23];//广告位id
                $data['user_id'] = Db::name('pid')->where('adzone_id', $data['adzone_id'])->value('user_id');
                $data['adzone_name'] = $v[24];

                $check = Db::name('goods_order')
                    ->where('goods_id',$data['goods_id'])
                    ->where('order_num',$data['order_num'])
                    ->find();
                    if ($data['state'] == 2) {
                        //订单结算
                        $user = Db::name('user')->where('id', $data['user_id'])->find();
                        $amount = round($v[16] / 2,2);
                        $arr = [
                            'user_id' => $data['user_id'],
                            'commission' => $amount,
                            'order_num' => $data['order_num'],
                            'time' => strtotime($v[14]),
                            'state' => 1,//1收入，2支出
                            'type' => 1,//1自己订单收入，2粉丝提成收入，3用户提现支出
                            'remark' => '订单' . $data['order_num'] . '收入'
                        ];
                        $check_profit = Db::name('profit')
                                    ->where('user_id',$data['user_id'])
                                    ->where('order_num',$data['order_num'])
                                    ->find();
                        if (empty($check_profit)) {
                            Db::name('profit')->insert($arr);
                            Db::name('user')->where('id',$data['user_id'])->setInc('total',$amount);
                            Db::name('user')->where('id',$data['user_id'])->setInc('commission',$amount);

                            //找父级
                            $parent_id = $user['parent_id'];
                            if($parent_id){
                                $parent = Db::name('user')->where('id',$parent_id)->find();
                                $ticheng = 0;
                                if($parent['status'] == 3){
                                    //初级合伙人
                                    $rule = Db::name('partner_rule')->where('status',3)->find();
                                    $level1 = $rule['level1']/100;
                                    $ticheng = round($amount*$level1,2);
                                }elseif($parent['status'] == 4){
                                    //高级合伙人
                                    $rule = Db::name('partner_rule')->where('status',4)->find();
                                    $level1 = $rule['level1']/100;
                                    $ticheng = round($amount*$level1,2);

                                }
                                $arr1 = [
                                    'user_id' => $parent_id,
                                    'commission' => $ticheng,
                                    'time' => strtotime($v[14]),
                                    'state' => 1,//1收入，2支出
                                    'type' => 2,//1自己订单收入，2粉丝提成收入，3用户提现支出
                                    'remark' => '粉丝' . $data['user_id'] . '订单' . $data['order_num'] . '收入'
                                ];

                                Db::name('profit')->insert($arr1);
                                Db::name('user')->where('id',$parent_id)->setInc('total',$ticheng);
                                Db::name('user')->where('id',$parent_id)->setInc('commission',$ticheng);
                                Db::name('user')->where('id',$parent_id)->setInc('rebate',$ticheng);

                                $grandsire = Db::name('user')->where('id',$parent['parent_id'])->find();
                                if($grandsire){
                                    //祖籍
                                    $t2 = 0;
                                    if($grandsire['status'] == 3){
                                        //初级合伙人
                                        $rule = Db::name('partner_rule')->where('status',3)->find();
                                        $level2 = $rule['level2']/100;
                                        $t2 = round($amount*$level2,2);
                                    }elseif($grandsire['status'] == 4){
                                        //高级合伙人
                                        $rule = Db::name('partner_rule')->where('status',4)->find();
                                        $level2 = $rule['level2']/100;
                                        $t2 = round($amount*$level2,2);

                                    }
                                    $arr2 = [
                                        'user_id' => $grandsire['id'],
                                        'commission' => $t2,
                                        'time' => strtotime($v[14]),
                                        'state' => 1,//1收入，2支出
                                        'type' => 2,//1自己订单收入，2粉丝提成收入，3用户提现支出
                                        'remark' => '粉丝' . $data['user_id'] . '订单' . $data['order_num'] . '收入'
                                    ];

                                    Db::name('profit')->insert($arr2);
                                    Db::name('user')->where('id',$parent_id)->setInc('total',$t2);
                                    Db::name('user')->where('id',$parent_id)->setInc('commission',$t2);
                                    Db::name('user')->where('id',$parent_id)->setInc('rebate',$t2);


                                }
                            }
                        }

                    }

                    if ($check) {
                        $success = Db::name('goods_order')->where('goods_id', $data['goods_id'])->where('order_num', $data['order_num'])->update($data);
                        if ($success) {
                            return json(['msg' => '插入或更新成功！', 'ok' => true]);
                        }
                    } else {
                        $datas[] = $data;
                    }
                    $i++;
                }

          /*  print_r($data);
            print_r($datas);*/



            Db::startTrans();
            try{
                $success = Db::name('goods_order')->insertAll($datas); //批量插入数据

                foreach($datas as $k =>$v){
                    if ($v['state'] == 2) {
                        //订单结算
                        $user = Db::name('user')->where('id', $v['user_id'])->find();
                        $amount = $v['member_actual'];
                       /* dump($amount);
                        die;*/
                        if($amount){
                            $arr = [
                                'user_id' => $v['user_id'],
                                'commission' => $amount,
                                'time' => strtotime($v['finish_time']),
                                'order_num' => $v['order_num'],
                                'state' => 1,//1收入，2支出
                                'type' => 1,//1自己订单收入，2粉丝提成收入，3用户提现支出
                                'remark' => '订单' . $v['order_num'] . '收入'
                            ];
                            $check_profit = Db::name('profit')
                                ->where('user_id',$v['user_id'])
                                ->where('order_num',$v['order_num'])
                                ->find();
                            if (empty($check_profit)) {
                                Db::name('profit')->insert($arr);
                                Db::name('user')->where('id',$v['user_id'])->setInc('total',$amount);
                                Db::name('user')->where('id',$v['user_id'])->setInc('commission',$amount);

                                $parent_id = $user['parent_id'];
                                if($parent_id){
                                    $parent = Db::name('user')->where('id',$parent_id)->find();
                                    $ticheng = 0;
                                    if($parent['status'] == 3){
                                        //初级合伙人
                                        $rule = Db::name('partner_rule')->where('status',3)->find();
                                        $level1 = $rule['level1']/100;

                                        $ticheng = round($amount*$level1,2);
                                    }elseif($parent['status'] == 4){
                                        //高级合伙人
                                        $rule = Db::name('partner_rule')->where('status',4)->find();
                                        $level1 = $rule['level1']/100;
                                        $ticheng = round($amount*$level1,2);

                                    }
                                    if($ticheng){
                                        $arr1 = [
                                            'user_id' => $parent_id,
                                            'commission' => $ticheng,
                                            'time' => strtotime($v['finish_time']),
                                            'state' => 1,//1收入，2支出
                                            'type' => 2,//1自己订单收入，2粉丝提成收入，3用户提现支出
                                            'remark' => '粉丝' . $v['user_id'] . '订单' . $v['order_num'] . '收入'
                                        ];

                                        Db::name('profit')->insert($arr1);
                                        Db::name('user')->where('id',$parent_id)->setInc('total',$ticheng);
                                        Db::name('user')->where('id',$parent_id)->setInc('commission',$ticheng);
                                        Db::name('user')->where('id',$parent_id)->setInc('rebate',$ticheng);

                                    }

                                    $grandsire = Db::name('user')->where('id',$parent['parent_id'])->find();
                                    if($grandsire){
                                        //祖籍
                                        $t2 = 0;
                                        if($grandsire['status'] == 3){
                                            //初级合伙人
                                            $rule = Db::name('partner_rule')->where('status',3)->find();
                                            $level2 = $rule['level2']/100;
                                            $t2 = round($amount*$level2,2);
                                        }elseif($grandsire['status'] == 4){
                                            //高级合伙人
                                            $rule = Db::name('partner_rule')->where('status',4)->find();
                                            $level2 = $rule['level2']/100;
                                            $t2 = round($amount*$level2,2);

                                        }
                                        if($t2){
                                            $arr2 = [
                                                'user_id' => $grandsire['id'],
                                                'commission' => $t2,
                                                'time' => strtotime($v['finish_time']),
                                                'state' => 1,//1收入，2支出
                                                'type' => 2,//1自己订单收入，2粉丝提成收入，3用户提现支出
                                                'remark' => '粉丝' . $v['user_id'] . '订单' . $v['order_num'] . '收入'
                                            ];

                                            Db::name('profit')->insert($arr2);
                                            Db::name('user')->where('id',$parent_id)->setInc('total',$t2);
                                            Db::name('user')->where('id',$parent_id)->setInc('commission',$t2);
                                            Db::name('user')->where('id',$parent_id)->setInc('rebate',$t2);

                                        }

                                    }
                                }
                            }
                        }



                    }

                }


                // 提交事务
                Db::commit();
                $error=$i-$success;
                return json(['msg'=>"总{$i}条，成功{$success}条，失败{$error}条。",'ok'=>true]);
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                $error = $e->getMessage();
                return json(['msg'=>$error,'ok'=>false]);
            }


        }else{
            // 上传失败获取错误信息
           $error = $file->getError();
            return json(['msg'=>$error,'ok'=>false]);
        }
    }

    /**
     *订单删除
     */
    public function order_del(){
        $id = intval(input('id'));
        if($id<=0){
            return json(['msg'=>'id必须为正整数','ok'=>false]);
        }
        $res = Db::name('goods_order')->where('id',$id)->delete();
        if($res){
            return json(['msg'=>'已删除','ok'=>true]);
        }else{
            return json(['msg'=>'删除失败','ok'=>false]);
        }
    }

    /**
     * 订单批量删除
     */
    public function order_datadel(){
        $ids = input('ids/a');
        /*dump($ids);
        die;*/
        $res = Db::name('goods_order')->whereIn('id',$ids)->delete();
        if($res){
            return json(['msg'=>'已删除','ok'=>true]);
        }else{
            return json(['msg'=>'删除失败','ok'=>false]);
        }
    }


    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    /**
     * 维权订单
     */
    public function refund(){
        $orders = Db::name('order_refund')
            ->order('id desc')
            ->paginate(10,false,['query'=>request()->param()])->each(function($item,$key){
                if(!empty($item['user_id'])){
                    $item['phone'] = Db::name('user')->where('id',$item['user_id'])->value('phone');

                }else{
                    $item['phone'] = '';
                }
                return $item;
            });
        /*echo "<pre>";
        print_r($orders);
        die;*/
        $count = Db::name('order_refund')->count();
        $this->assign([
            'orders'=>$orders,
            'count'=>$count,
            'empty'=>'<tr class="text-c va-m empty"><td colspan="12">暂无数据</td></tr>'
        ]);
        return $this->fetch('goods:refund');
    }

    /**
     * 维权订单 搜索
     */
    public function search_refund(){
        $common = trim(input('common'));
        if(empty($common)){
            return json(['msg'=>'搜索条件不能为空！','ok'=>false]);
        }
        $orders = Db::name('order_refund')
            ->where('order_num','like','%'.$common.'%')
            ->whereOr('title','like','%'.$common.'%')
            ->order('id desc')
            ->paginate(10,false,['query'=>request()->param()])->each(function($item,$key){
                if(!empty($item['user_id'])){
                    $item['phone'] = Db::name('user')->where('id',$item['user_id'])->value('phone');

                }else{
                    $item['phone'] = '';
                }
                return $item;
            });

        $count = Db::name('order_refund')
            ->where('order_num','like','%'.$common.'%')
            ->whereOr('title','like','%'.$common.'%')
            ->count();
        if(!empty($orders[0])){
            $this->assign([
                'orders'=>$orders,
                'count'=>$count
            ]);
            return $this->fetch('goods:refund');
        }else{
            return json(['msg'=>'没有符合条件的结果！','ok'=>false]);
        }

    }

    /**
     * 维权上传
     */
    public function refund_add(){
        $objPHPExcel = new \PHPExcel();

        //获取表单上传文件
        $file = request()->file('excel');
        //  print_r($file);die;
        $info = $file->validate(['size'=>10485760,'ext'=>'xlsx,xls,csv'])->move(ROOT_PATH . 'public' . DS . 'excel');
        if($info) {
            $exclePath = $info->getSaveName();  //获取文件名
            $file_name = ROOT_PATH . 'public' . DS . 'excel' . DS . $exclePath;   //上传文件的地址
            $objReader = \PHPExcel_IOFactory::createReader('Excel2007');
            if(!$objReader->canRead($file_name)) {
                $objReader = \PHPExcel_IOFactory::createReader('Excel5');
            }
            $obj_PHPExcel = $objReader->load($file_name, $encode = 'utf-8');  //加载文件内容,编码utf-8

            $excel_array = $obj_PHPExcel->getsheet(0)->toArray();   //转换为数组格式
            array_shift($excel_array);  //删除第一个数组(标题);
            /*print_r($excel_array);
            die;*/

            $data =  $datas = [];
            $i    = 0;
            foreach($excel_array as $k=>$v) {
                $data['order_num'] = $v[0];
                $data['subnumber'] = $v[1];
                $data['title'] = $v[2];
                $data['fact'] = $v[3];
                $data['behoove'] = $v[4];
                $data['state'] = $v[5];
                $data['finish_time'] = $v[6];
                $data['create_time'] = $v[7];
                $data['over_time'] = $v[8];
                $data['user_id'] = Db::name('user_order')->where('order_num', $data['order_num'])->value('user_id');

                $check = Db::name('order_refund')
                    ->where('subnumber',$data['subnumber'])
                    ->where('order_num',$data['order_num'])
                    ->find();
              //  $user_id = Db::name('user_order')->where('order_num', $data['order_num'])->value('user_id');
                if( $data['user_id']){
                    $s =  Db::name('order_refund')
                        ->where('order_num', $data['order_num'])
                        ->update(['user_id' =>  $data['user_id']]);
                    if(!empty($data['over_time'])||!empty($data['fact'])){
                        $amount = round( $data['fact'] / 2,2);
                        $arr = [
                            'user_id' =>  $data['user_id'],
                            'commission' => $amount,
                            'time' => strtotime($data['over_time']),
                            'state' => 1,//1收入，2支出
                            'type' => 4,//1自己订单收入，2粉丝提成收入，3用户提现支出，4维权订单收入，5粉丝维权订单收入
                            'remark' => '维权订单' . $data['order_num'] . '收入'
                        ];
                        $check_profit = Db::name('profit')
                            ->where('user_id',  $data['user_id'])
                            ->where('type', 4)
                            ->where('remark', '维权订单' . $data['order_num'] . '收入')
                            ->find();
                        if (empty($check_profit)) {
                            Db::name('profit')->insert($arr);
                            Db::name('user')->where('id', $data['user_id'])->setInc('total',$amount);
                            Db::name('user')->where('id', $data['user_id'])->setInc('commission',$amount);
                        }
                        $user = Db::name('user')->where('id', $data['user_id'])->find();
                        $parent = $user['parent_id'];
                        if(!empty($parent)){
                            $fan =  $data['fact'] / 2;
                            //父级存在
                            $status = Db::name('user')->where('id',$parent)->value('status');
                            //1，无效粉丝，2有效粉丝，3初级合伙人，4高级合伙人
                            $rebate = 0;
                            if($status==3){
                                $rule = Db::name('partner_rule')->where('status',3)->find();
                                $level1 = $rule['level1']/100;
                                $rebate = round($fan*$level1,2);
                            }elseif($status==4){
                                $rule = Db::name('partner_rule')->where('status',4)->find();
                                $level1 = $rule['level1']/100;
                                $rebate = round($fan*$level1,2);
                            }

                            $arr = [
                                'user_id' => $parent,
                                'commission' => $rebate,
                                'time' => strtotime($data['over_time']),
                                'state' => 1,//1收入，2支出
                                'type' => 5,//1自己订单收入，2粉丝提成收入，3用户提现支出，4维权订单收入，5粉丝维权订单收入
                                'remark' => '维权订单' . $data['order_num'] . '收入'
                            ];
                            $check_profit = Db::name('profit')
                                ->where('user_id', $parent)
                                ->where('type', 5)
                                ->where('remark', '维权订单' . $data['order_num'] . '收入')
                                ->find();
                            if (empty($check_profit)) {
                                Db::name('profit')->insert($arr);
                                Db::name('user')->where('id',$parent)->setInc('total',$rebate);
                                Db::name('user')->where('id',$parent)->setInc('commission',$rebate);
                                Db::name('user')->where('id',$parent)->setInc('rebate',$rebate);
                            }
                            $grandsire = Db::name('user')->where('id',$parent['parent_id'])->find();
                            if($grandsire){
                                $fan =  $data['fact'] / 2;
                                //祖籍存在
                                if($status==3){
                                    $rule = Db::name('partner_rule')->where('status',3)->find();
                                    $level2 = $rule['level2']/100;
                                    $rebate = round($fan*$level2,2);
                                }elseif($status==4){
                                    $rule = Db::name('partner_rule')->where('status',4)->find();
                                    $level2 = $rule['level2']/100;
                                    $rebate = round($fan*$level2,2);
                                }


                                $arr = [
                                    'user_id' => $grandsire['id'],
                                    'commission' => $rebate,
                                    'time' => strtotime($data['over_time']),
                                    'state' => 1,//1收入，2支出
                                    'type' => 5,//1自己订单收入，2粉丝提成收入，3用户提现支出，4维权订单收入，5粉丝维权订单收入
                                    'remark' => '维权订单' . $data['order_num'] . '收入'
                                ];
                                $check_profit = Db::name('profit')
                                    ->where('user_id', $grandsire['id'])
                                    ->where('type', 5)
                                    ->where('remark', '维权订单' . $data['order_num'] . '收入')
                                    ->find();
                                if (empty($check_profit)) {
                                    Db::name('profit')->insert($arr);
                                    Db::name('user')->where('id',$grandsire['id'])->setInc('total',$rebate);
                                    Db::name('user')->where('id',$grandsire['id'])->setInc('commission',$rebate);
                                    Db::name('user')->where('id',$grandsire['id'])->setInc('rebate',$rebate);
                                }

                            }
                        }
                    }
                }

                if ($check) {
                    $success = Db::name('order_refund')
                        ->where('subnumber',$data['subnumber'])
                        ->where('order_num', $data['order_num'])
                        ->update($data);
                    if ($success) {
                        return json(['msg' => '插入或更新成功！', 'ok' => true]);
                    }
                } else {
                    $datas[] = $data;
                }
                $i++;
            }
            Db::startTrans();
            try{
                $success = Db::name('order_refund')->insertAll($datas); //批量插入数据
                if($success){
                    foreach($datas as $k =>$v){
                            if(!empty($data['finish_time'])||!empty($v['fact'])){
                                $amount = round( $data['fact'] / 2,2);
                                $arr = [
                                    'user_id' => $v['user_id'],
                                    'commission' => $amount,
                                    'time' => strtotime($v['over_time']),
                                    'state' => 1,//1收入，2支出
                                    'type' => 4,//1自己订单收入，2粉丝提成收入，3用户提现支出，4维权订单收入，5粉丝维权订单收入
                                    'remark' => '维权订单' . $v['order_num'] . '收入'
                                ];
                                $check_profit = Db::name('profit')
                                    ->where('user_id', $v['user_id'])
                                    ->where('type', 4)
                                    ->where('remark', '维权订单' . $v['order_num'] . '收入')
                                    ->find();
                                if (empty($check_profit)) {
                                    Db::name('profit')->insert($arr);
                                    Db::name('user')->where('id',$v['user_id'])->setInc('total',$amount);
                                    Db::name('user')->where('id',$v['user_id'])->setInc('commission',$amount);
                                }
                                $user = Db::name('user')->where('id',$v['user_id'])->find();
                                $parent = $user['parent_id'];
                                if(!empty($parent)){
                                    $fan =  $data['fact'] / 2;
                                    //父级存在
                                    $status = Db::name('user')->where('id',$parent)->value('status');
                                    //1，无效粉丝，2有效粉丝，3初级合伙人，4高级合伙人
                                    $rebate = 0;
                                    if($status==3){
                                        $rule = Db::name('partner_rule')->where('status',3)->find();
                                        $level1 = $rule['level1']/100;
                                        $rebate = round($fan*$level1,2);
                                    }elseif($status==4){
                                        $rule = Db::name('partner_rule')->where('status',4)->find();
                                        $level1 = $rule['level1']/100;
                                        $rebate = round($fan*$level1,2);
                                    }

                                    $arr = [
                                        'user_id' => $parent,
                                        'commission' => $rebate,
                                        'time' => strtotime($v['over_time']),
                                        'state' => 1,//1收入，2支出
                                        'type' => 5,//1自己订单收入，2粉丝提成收入，3用户提现支出，4维权订单收入，5粉丝维权订单收入
                                        'remark' => '维权订单' . $v['order_num'] . '收入'
                                    ];
                                    $check_profit = Db::name('profit')
                                        ->where('user_id', $parent)
                                        ->where('type', 5)
                                        ->where('remark', '维权订单' . $v['order_num'] . '收入')
                                        ->find();
                                    if (empty($check_profit)) {
                                        Db::name('profit')->insert($arr);
                                        Db::name('user')->where('id',$parent)->setInc('total',$rebate);
                                        Db::name('user')->where('id',$parent)->setInc('commission',$rebate);
                                        Db::name('user')->where('id',$parent)->setInc('rebate',$rebate);
                                    }
                                    $grandsire = Db::name('user')->where('id',$parent['parent_id'])->find();
                                    if($grandsire){
                                        $fan =  $data['fact'] / 2;
                                        //祖籍存在

                                        if($status==3){
                                            $rule = Db::name('partner_rule')->where('status',3)->find();
                                            $level2 = $rule['level2']/100;
                                            $rebate = round($fan*$level2,2);
                                        }elseif($status==4){
                                            $rule = Db::name('partner_rule')->where('status',4)->find();
                                            $level2 = $rule['level2']/100;
                                            $rebate = round($fan*$level2,2);
                                        }

                                        $arr = [
                                            'user_id' => $grandsire['id'],
                                            'commission' => $rebate,
                                            'time' => strtotime($v['over_time']),
                                            'state' => 1,//1收入，2支出
                                            'type' => 5,//1自己订单收入，2粉丝提成收入，3用户提现支出，4维权订单收入，5粉丝维权订单收入
                                            'remark' => '维权订单' . $v['order_num'] . '收入'
                                        ];
                                        $check_profit = Db::name('profit')
                                            ->where('user_id', $grandsire['id'])
                                            ->where('type', 5)
                                            ->where('remark', '维权订单' . $v['order_num'] . '收入')
                                            ->find();
                                        if (empty($check_profit)) {
                                            Db::name('profit')->insert($arr);
                                            Db::name('user')->where('id',$grandsire['id'])->setInc('total',$rebate);
                                            Db::name('user')->where('id',$grandsire['id'])->setInc('commission',$rebate);
                                            Db::name('user')->where('id',$grandsire['id'])->setInc('rebate',$rebate);
                                        }

                                    }
                                }
                            }
                        }

                }
                // 提交事务
                Db::commit();
                $error=$i-$success;
                return json(['msg'=>"总{$i}条，成功{$success}条，失败{$error}条。",'ok'=>true]);
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                $error = $e->getMessage();
                return json(['msg'=>$error,'ok'=>false]);
            }


        }else{
            // 上传失败获取错误信息
            $error = $file->getError();
            return json(['msg'=>$error,'ok'=>false]);
        }
    }

    /**
     * 维权订单删除
     */
    public function refund_del(){
        $id = intval(input('id'));
        if($id<=0){
            return json(['msg'=>'id必须为正整数','ok'=>false]);
        }
        $res = Db::name('order_refund')->where('id',$id)->delete();
        if($res){
            return json(['msg'=>'已删除','ok'=>true]);
        }else{
            return json(['msg'=>'删除失败','ok'=>false]);
        }
    }

    /**
     * 维权订单 批量删除
     */
    public function refund_datadel(){
        $ids = input('ids/a');
        /*dump($ids);
        die;*/
        $res = Db::name('order_refund')->whereIn('id',$ids)->delete();
        if($res){
            return json(['msg'=>'已删除','ok'=>true]);
        }else{
            return json(['msg'=>'删除失败','ok'=>false]);
        }
    }

    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    /**
     * 热搜词列表
     */
    public function hot(){
        $keyword = Db::name('hot_search')
            ->order('id desc')
            ->paginate(10,false,['query'=>request()->param()]);
        $count = Db::name('hot_search')->count();
        $this->assign([
            'keyword'=>$keyword,
            'count'=>$count,
            'empty'=>'<tr class="text-c va-m empty"><td colspan="5">暂无数据</td></tr>'
        ]);
        return view('');
    }

    /**
     * 添加
     */
    public function hot_add(){
        $keyword = trim(input('keyword'));
        if(empty($keyword)){
            return json(['msg'=>'热搜词不能为空','ok'=>false]);
        }
        $check = Db::name('hot_search')->where('keyword',$keyword)->find();
        if($check){
            return json(['msg'=>'热搜词已经存在','ok'=>false]);
        }
        $result = Db::name('hot_search')->insert(['keyword'=>$keyword]);
        if($result){
            return json(['msg'=>'添加成功','ok'=>true]);
        }else{
            return json(['msg'=>'添加失败','ok'=>false]);
        }
    }
    /**
     * 修改
     */
    public function hot_save(){
        $keyword = trim(input('keyword'));
        $id      = intval(input('id'));
        if(empty($keyword)){
            return json(['msg'=>'热搜词不能为空','ok'=>false]);
        }
        $check = Db::name('hot_search')->whereNotIn('id',$id)->where('keyword',$keyword)->find();
        if($check){
            return json(['msg'=>'热搜词已经存在','ok'=>false]);
        }
        $result = Db::name('hot_search')->where('id',$id)->update(['keyword'=>$keyword]);
        if($result){
            return json(['msg'=>'修改成功','ok'=>true]);
        }else{
            return json(['msg'=>'修改失败','ok'=>false]);
        }
    }

    /**
     * 启用
     */
    public function hot_start(){
        $id      = intval(input('id'));
        if($id<=0){
            return json(['msg'=>'id必须为正整数','ok'=>false]);
        }
        $result = Db::name('hot_search')->where('id',$id)->update(['is_down'=>1]);
        if($result){
            return json(['msg'=>'启用成功','ok'=>true]);
        }else{
            return json(['msg'=>'启用失败','ok'=>false]);
        }
    }

    /**
     * 停用
     */
    public function hot_stop(){
        $id      = intval(input('id'));
        if($id<=0){
            return json(['msg'=>'id必须为正整数','ok'=>false]);
        }
        $result = Db::name('hot_search')->where('id',$id)->update(['is_down'=>2]);
        if($result){
            return json(['msg'=>'停用成功','ok'=>true]);
        }else{
            return json(['msg'=>'停用失败','ok'=>false]);
        }
    }
    /**
     * 删除
     */
    public function hot_del(){
        $id      = intval(input('id'));
        if($id<=0){
            return json(['msg'=>'id必须为正整数','ok'=>false]);
        }
        $result = Db::name('hot_search')->where('id',$id)->delete();
        if($result){
            return json(['msg'=>'已删除','ok'=>true]);
        }else{
            return json(['msg'=>'删除失败','ok'=>false]);
        }
    }





}